package com.haidong.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

// 使用Request获取请求数据要注意getReader和getInputStream
// 虽然名字是getReader,实际上返回的是缓冲文本流BufferReader,所以不可用低级流接收
// getInputStream也是一样,返回值是ServletInputStream

@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //getMethod,其实在这里没用,因为能进get方法肯定是get请求
        String method = req.getMethod();
        System.out.println(method);
        //getContextPath()获取虚拟目录(项目的访问路径)
        String contextPath = req.getContextPath();
        System.out.println(contextPath);
        //getRequestURL()获取URL(资源定位符)
        StringBuffer url = req.getRequestURL();
        System.out.println(url.toString());
        //getRequestURI()获取URI(获取资源标识符/相对路径)
        String uri = req.getRequestURI();
        System.out.println(uri);
        //getQueryString()获取get请求参数
        String queryString = req.getQueryString();
        System.out.println(queryString);

        //请求头是以键值对书写的,通过键名取值,这里演示获取浏览器的版本
        String agent = req.getHeader("user-agent");
        System.out.println(agent);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //可以通过获取字节输入流或者文本流
        //完成请求后,请求对象会消失,流也就消失了,不需要手动关闭
        BufferedReader br = req.getReader();
        //读取数据
        String line = br.readLine();
        System.out.println(line);
    }
}
